//
//  ViewController.m
//  ExpandTableView
//
//  Created by ZYK on 16/2/16.
//  Copyright © 2016年 ZYK. All rights reserved.
//

#import "TrainViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "TrainVideoTableViewCell.h"
#import "CommunicationManager.h"
#import "TrainVideoWebViewController.h"
#import "TrainingCategory.h"
#import <MJRefresh/MJRefresh.h>
#import "TrackVideoViewController.h"

static const CGFloat kSectionHeight    = 39.0f; //section的高度
static const CGFloat kCellHeight       = 84.0f; //内容cell的高度

static NSString * const kVideoSegue = @"VideoSegue";    // 网页视频

#define kMainColor [UIColor colorWithRed:38/255.0f green:194/255.0f blue:158/255.0f alpha:1.0]

@interface TrainViewController ()<UIGestureRecognizerDelegate>
@property (strong, nonatomic) NSIndexPath *indexPath;

@property (nonatomic, strong) NSArray *trainingCategories;

@end

@implementation TrainViewController

#pragma mark - View LifeCycle

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configureMTableView];
    [self addHeaderRefreshControl];
    
}
- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.trainingCategories == nil) {
        [self.mTableView.tableView.mj_header beginRefreshing];
    }
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:kVideoSegue]) {
        
        TrainVideoWebViewController *controller = segue.destinationViewController;
        TrainingVideo *video = (TrainingVideo *)sender;
        controller.urlStr = video.url;
        controller.title = video.name;
    }
}

#pragma mark - Private Method

- (void)addHeaderRefreshControl
{
    __weak TrainViewController *weakSelf = self;
    [self.mTableView.tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
        [weakSelf performRequestTrainingVideoList];
    }];
}

#pragma mark - Networking

- (void)performRequestTrainingVideoList
{
    YFTrainingApi *trainingVideoListApi = [YFTrainingApi getTrainTennisCoachVideoWithisHDVideo:NO];
    [[YFNetworkingService sharedInstance] sendRequest:trainingVideoListApi callback:^(BOOL success, id result, NSError *error) {
        if (success) {
            self.trainingCategories = [NSArray modelArrayWithClass:[TrainingCategory class] json:[result responseInfo]];
            [self.mTableView reloadData];
        }
        [self.mTableView.tableView.mj_header endRefreshing];
    }];
}

#pragma mark - Customize Appearance

- (void)configureMTableView
{
    self.mTableView = [[TQMultistageTableView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64.0f)];
    self.mTableView.dataSource = self;
    self.mTableView.delegate   = self;
    self.mTableView.backgroundColor = [UIColor clearColor];
    self.mTableView.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mTableView.tableView.separatorColor = [UIColor redColor];
    [self.mTableView.tableView registerNib:[UINib nibWithNibName:@"TrainVideoTableViewCell" bundle:nil] forCellReuseIdentifier:@"TrainVideoTableViewCell"];
    [self.view addSubview:self.mTableView];
}

#pragma mark - TQTableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(TQMultistageTableView *)mTableView
{
    return [self.trainingCategories count];
}

- (NSInteger)mTableView:(TQMultistageTableView *)mTableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.trainingCategories[section] videoList] count];
}

- (UITableViewCell *)mTableView:(TQMultistageTableView *)mTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrainVideoTableViewCell *cell = [mTableView dequeueReusableCellWithIdentifier:@"TrainVideoTableViewCell" forIndexPath:indexPath];
    
    TrainingVideo *model = [self.trainingCategories[indexPath.section] videoList][indexPath.row];
    [cell configureWithCategoryVideo:model];
    
    return cell;
}

#pragma mark - Table view delegate

//点击section的时候代理请求数据
- (void)mTableView:(TQMultistageTableView *)mTableView requestDataAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.mTableView openOrCloseCellWithTouchType:TQHeaderLineTouch forIndexPath:indexPath];
}

- (void)mTableView:(TQMultistageTableView *)mTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TrainingVideo *video = [self.trainingCategories[indexPath.section] videoList][indexPath.row];
    
    if ([YFCheckNetworkStatus shareInstance].networkStatus == AFNetworkReachabilityStatusReachableViaWiFi) {
        [self performSegueWithIdentifier:kVideoSegue sender:video];
    }else {
        FUIAlertView *alertView = [[FUIAlertView alloc] initWithTitle:NSLocalizedString(@"Reminder", nil) message:NSLocalizedString(@"Viewing this video under cellular network might result in high data usage.   Proceed / Cancel?", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Proceed", nil), nil];
        [alertView customizeAppearance];
        
        alertView.onOkAction = ^{
            [self performSegueWithIdentifier:kVideoSegue sender:video];
        };
        [alertView show];
    }
}

- (CGFloat)mTableView:(TQMultistageTableView *)mTableView heightForHeaderInSection:(NSInteger)section
{
    return kSectionHeight;
}

- (CGFloat)mTableView:(TQMultistageTableView *)mTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCellHeight;
}

- (UIView *)mTableView:(TQMultistageTableView *)mTableView viewForHeaderInSection:(NSInteger)section;
{
    UIView *header = [[[NSBundle mainBundle] loadNibNamed:@"TrainHeaderView" owner:self options:nil] lastObject];
    UILabel *label = (UILabel *)[header viewWithTag:100];
    label.text = [self.trainingCategories[section] name];
    
    return header;
}

#pragma mark - Header Open Or Close

- (void)mTableView:(TQMultistageTableView *)mTableView willOpenHeaderAtSection:(NSInteger)section
{
    NSLog(@"Open Header ----%ld",(long)section);
}

- (void)mTableView:(TQMultistageTableView *)mTableView willCloseHeaderAtSection:(NSInteger)section
{
    NSLog(@"Close Header ---%ld",(long)section);
}

#pragma mark - Row Open Or Close

- (void)mTableView:(TQMultistageTableView *)mTableView willOpenRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Open Row ----%ld",(long)indexPath.row);
}

- (void)mTableView:(TQMultistageTableView *)mTableView willCloseRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Close Row ----%ld",(long)indexPath.row);
}

@end
